from django.db import models

import datetime

# Create your models here.

class Spider(models.Model):
    id = models.AutoField(primary_key=True)
    ip = models.GenericIPAddressField(default="127.0.0.1")
    port = models.CharField(max_length=10, default=6800)  # 代码所在的地址(scrapyd服务地址) 
    project_name = models.CharField(max_length=50)  # 爬虫项目名称
    spider_name = models.CharField(max_length=50)  # 爬虫名称
    desc = models.TextField()    # 爬虫介绍（功能与参数等）
    is_valid = models.BooleanField(default=True)  # 是否可用
    domain = models.CharField(max_length=50, default="common")
    update_time = models.DateTimeField(auto_now=True)

    # 定义显示的顺序
    @classmethod
    def get_sorted_keys(cls):
        keys = ("id", "project_name", "spider_name", "domain", "ip", "port", "desc", "is_valid")
        return keys

    def __str__(self):
        return "%s.%s" % (self.project_name, self.spider_name)

    class Meta:
        ordering = ["update_time"]


PERIOD_CHOICES = (("seconds", "秒"),
                  ("minutes", "分钟"),
                  ("hours", "小时"),
                  ("days", "天"),
                  ("weeks", "周"))


class Task(models.Model):
    spider = models.ForeignKey(Spider, on_delete=models.CASCADE)  # 任务对应的的爬虫
    task_id = models.IntegerField()
    task_name = models.CharField(max_length=50)    # 任务名称 
    setting = models.TextField(blank=True)    # scrapy配置参数
    spider_args = models.CharField(max_length=100, blank=True)  # 爬虫实例化参数
    
    every = models.IntegerField(default=5)
    period = models.CharField(choices=PERIOD_CHOICES, max_length=10, default="minutes")

    is_timing = models.BooleanField(default=True)  # 是否时定时任务

    def __str__(self):
        return self.task_name

    class Meta:
        ordering = ["task_id"]

